package com.guagua.vas.util;
/**
 * 北京八度互联科技有限公司版权所有
 * Copyright (C) Badu Corporation. All Rights Reserved
 */
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
/** ******************************************************************
* 类概要: 模拟http请求类，实现文件、表单的发送功能
* @author 郑国英
* @version 2012-6-1 上午10:01:00
*******************************************************************
*/
public class HTTPUtil {
	
	/**
	 * 函数说明：模拟http get请求，非二进制流传输的数据
	 * <br/>
	 *
	 * @param url 类型:(String)；<br/> 
	 * 含义:   服务器的URL地址及表单参数<br/>；
	 * @return 返回相应结果，即页面输出结果
	 *         
     */
	public static String get(String url) {
		String rs = null;
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		try {
				//请求超时
			httpclient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
				//读取超时
			httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);
			HttpResponse response=httpclient.execute(httpGet);
			 
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				rs = EntityUtils.toString(entity, HTTP.UTF_8);
				entity.consumeContent();
			}
		}
		catch (ClientProtocolException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		
		if (rs == null)
			return rs;
		return rs.replaceAll("[(\r)(\n)(\t)]", "");
	}
	/**
	 * 函数说明：模拟http请求，非二进制流传输的数据
	 * <br/>
	 *
	 * @param url 类型:(String)；<br/> 
	 * 含义:   服务器的URL地址<br/>；
	 * @param map 类型:(Map<String, String>)；<br/> 
	 * 含义:  传递表单集合<br/>；
	 * @return 返回相应结果，即页面输出结果
	 *         
     */
	public static String post(String url, Map<String, String> map) {

		String rs = null;

		HttpClient httpclient = new DefaultHttpClient();
		try {
			HttpPost post = new HttpPost(url);
			Iterator<Entry<String, String>> it = map.entrySet().iterator();
			StringBuilder body = new StringBuilder();
			while (it.hasNext()) {
				Entry<String, String> sEntry = it.next();
				/*if (sEntry.getKey().equals("mw") || sEntry.getKey().equals("mh"))
					body.append(sEntry.getValue());
				else*/
					body.append("&").append(sEntry.getKey()).append("=").append(sEntry.getValue());
			}
			
			StringEntity myEntity = new StringEntity(body.substring(1), HTTP.UTF_8);
			myEntity.setContentType("application/x-www-form-urlencoded;charset=UTF-8");

			post.setEntity(myEntity);
			//请求超时
			httpclient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
			//读取超时
			httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);
			post.addHeader(HttpMethodParams.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
			//post.setHeader("Content-Type", "text/plain;charset=UTF-8");
			HttpResponse response = httpclient.execute(post);
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				rs = EntityUtils.toString(entity, HTTP.UTF_8);
				entity.consumeContent();
			}
		}
		catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (rs == null)
			return rs;
		return rs.replaceAll("[(\r)(\n)(\t)]", "");
	}
	/**
	 * 函数说明：模拟http请求，二进制流传输的数据，不包含其他参数
	 * <br/>
	 *
	 * @param url 类型:(String)；<br/> 
	 * 含义:   服务器的URL地址<br/>；
	 * @param file 类型:(File)；<br/> 
	 * 含义:  文件句柄，二进制流传输<br/>；
	 * @return 返回相应结果，即页面输出结果
	 *         
     */
	public String postFile(String url, File file) throws ClientProtocolException, IOException {
		Map<String, String> map = new HashMap();
		return postFileAndParam(url, file, map);
	}
	/**
	 * 函数说明：模拟http请求，二进制流传输的数据，并且可以传输表单信息
	 * <br/>
	 *
	 * @param url 类型:(String)；<br/> 
	 * 含义:   服务器的URL地址<br/>；
	 * @param file 类型:(File)；<br/> 
	 * 含义:  文件句柄，二进制流传输<br/>；
	 * @param map 类型:(Map<String, String>)；<br/> 
	 * 含义:  传递表单集合<br/>；
	 * @return 返回相应结果，即页面输出结果
	 *         
     */
	public static String postFileAndParam(String url, File file, Map<String, String> map) throws ClientProtocolException, IOException {
		String rs = "";
		HttpClient httpclient = new DefaultHttpClient();
		// 请求处理页面
		HttpPost httppost = new HttpPost(url);
		// 创建待处理的文件
		FileBody fBody = new FileBody(file);

		// 对请求的表单域进行填充
		MultipartEntity reqEntity = new MultipartEntity();
		reqEntity.addPart("file", fBody);

		// 设置请求
		httppost.setEntity(reqEntity);
		

		Iterator<Entry<String, String>> it = map.entrySet().iterator();
		StringBuilder body = new StringBuilder();
		while (it.hasNext()) {
			Entry<String, String> sEntry = it.next();
			StringBody stb = new StringBody(sEntry.getValue());
			reqEntity.addPart(sEntry.getKey(), stb);
		}

		// 执行
		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity = response.getEntity();

		if (entity != null) {
			rs = EntityUtils.toString(entity);
			entity.consumeContent();
		}
		if (rs == null)
			return rs;
		return rs.replaceAll("[(\r)(\n)(\t)]", "");
	}

	private synchronized static String urlEncode(String url, String code) {
		if (null != url) {
			try {
				return URLEncoder.encode(url, code);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		return url;
	}
}
